#!/usr/bin/env python3
"""
数据库初始化脚本
用于创建数据库表和初始化数据
"""
import sys
import os

# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from flask import Flask
from config import get_config
from services.shared.database import init_db
from services.shared.models import db
from services.shared.models.user import User
from services.shared.models.task import Task, TaskExecution
from services.shared.models.system import SystemLog


def create_app():
    """创建Flask应用实例"""
    app = Flask(__name__)
    
    # 从配置类加载配置
    config_class = get_config()
    app.config.from_object(config_class)
    
    # 确保SQLALCHEMY_DATABASE_URI被正确设置
    if not app.config.get('SQLALCHEMY_DATABASE_URI'):
        database_url = os.getenv('DATABASE_URL')
        if database_url:
            app.config['SQLALCHEMY_DATABASE_URI'] = database_url
        else:
            # 检查必需的数据库环境变量
            required_vars = ['MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_HOST', 'MYSQL_PORT', 'MYSQL_DATABASE']
            missing_vars = [var for var in required_vars if not os.getenv(var)]
            if missing_vars:
                raise ValueError(f"缺少必需的数据库环境变量: {', '.join(missing_vars)}")
            
            # 从环境变量构建数据库URL
            mysql_user = os.getenv('MYSQL_USER')
            mysql_password = os.getenv('MYSQL_PASSWORD')
            mysql_host = os.getenv('MYSQL_HOST')
            mysql_port = int(os.getenv('MYSQL_PORT'))
            mysql_database = os.getenv('MYSQL_DATABASE')
            database_url = f"mysql+pymysql://{mysql_user}:{mysql_password}@{mysql_host}:{mysql_port}/{mysql_database}"
            app.config['SQLALCHEMY_DATABASE_URI'] = database_url
    
    # 设置其他必要的配置
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    return app


def init_database():
    """初始化数据库"""
    print("开始初始化数据库...")
    
    app = create_app()
    
    with app.app_context():
        # 初始化数据库
        init_db(app)
        print("数据库初始化完成！")
        
        # 显示统计信息
        from services.shared.database import get_db_stats
        stats = get_db_stats()
        print(f"用户数量: {stats['users_count']}")
        print(f"任务数量: {stats['tasks_count']}")
        print(f"执行记录数量: {stats['executions_count']}")


def reset_database():
    """重置数据库"""
    print("警告：这将删除所有数据！")
    confirm = input("确认重置数据库？(y/N): ")
    
    if confirm.lower() == 'y':
        app = create_app()
        with app.app_context():
            db.drop_all()
            print("数据库已清空")
            init_db(app)
            print("数据库重置完成！")
    else:
        print("操作已取消")


if __name__ == '__main__':
    import argparse
    
    parser = argparse.ArgumentParser(description='数据库管理工具')
    parser.add_argument('action', choices=['init', 'reset'], 
                       help='操作类型: init(初始化) 或 reset(重置)')
    
    args = parser.parse_args()
    
    if args.action == 'init':
        init_database()
    elif args.action == 'reset':
        reset_database()